package cn.stylefeng.guns.modular.api;

import cn.stylefeng.guns.api.core.util.JwtTokenUtil;
import cn.stylefeng.guns.modular.business.model.params.OrderParam;
import cn.stylefeng.guns.modular.business.model.params.OrderQueryParam;
import cn.stylefeng.guns.modular.business.model.result.OrderResult;
import cn.stylefeng.guns.modular.business.service.OrderService;
import cn.stylefeng.guns.sys.core.util.StringUtils;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;


/**
 * 订单表控制器
 *
 * @author jwj
 * @Date 2019-07-12 14:20:25
 */
@RestController
@RequestMapping("/gunsApi/order")
public class OrderApi extends BaseController {

    @Autowired
    private OrderService orderService;

    /**
     * 提交订单
     * @param orderParam
     * @return
     */
    @ApiOperation("提交订单")
    @PostMapping("/create")
    public ResponseData create(@RequestBody OrderParam orderParam) {
        String checkStr = orderParam.checkParam();
        if (!StringUtils.isEmpty(checkStr)) {
            return ResponseData.error(700, checkStr);
        }
        return orderService.create(orderParam);
    }

    /**
     * 按条件查询我的订单
     * @param request
     * @param orderQueryParam
     * @return
     */
    @ApiOperation("按条件分页查询我的订单")
    @PostMapping("/getMyOrders")
    public ResponseData getMyOrders(HttpServletRequest request, @RequestBody OrderQueryParam orderQueryParam) {
        String authorization = request.getHeader("Authorization");
        String[] token = authorization.split(" ");
        Long userId = Long.valueOf(JwtTokenUtil.getUsernameFromToken(token[1]));
        orderQueryParam.setOwnerUserId(userId);
        if (orderQueryParam.getCurrent() == null) {
            return ResponseData.error(700, "分页参数错误");
        }

        if (orderQueryParam.getSize() == null) {
            return ResponseData.error(700, "分页参数错误");
        }
        Page page = new Page(orderQueryParam.getCurrent(), orderQueryParam.getSize());

        if(StringUtils.isNotEmpty(orderQueryParam.getStartTime())) {
            orderQueryParam.setStartTime(orderQueryParam.getStartTime() + " 00:00:00");
            orderQueryParam.setEndTime(orderQueryParam.getEndTime() + " 23:59:59");
        }
        Page<OrderResult> myOrders = orderService.getMyOrders(page, orderQueryParam);
        return ResponseData.success(myOrders);
    }
}


